%%%% Hodrick-Prescott Filter - (8/22/2022) %%%%
%% Detrended data: X_tilde
%% Data Series: X
%% Smoothing Parameter: lambda
%% Note: I assume that data is in logs when it is uploaded into the code

function X_tilde = HP_Filter(X,lambda)

%%%% Set Parameters %%%%
N = length(X);

%%%% Initialize Matrix A %%%%
A = zeros(N,N);

%%%% Solve for Row 1 %%%%
A(1,1) = 1.0 + lambda;
A(1,2) = -2.0*lambda;
A(1,3) = lambda;

%%%% Solve for Row 2 %%%%
A(2,1) = -2.0*lambda;
A(2,2) = 1.0 + 5.0*lambda;
A(2,3) = -4.0*lambda;
A(2,4) = lambda;

%%%% Solve for Rows 3 through N-2 %%%%
for t = 3:(N-2)
    A(t,t-2) = lambda;
    A(t,t-1) = -4.0*lambda;
    A(t,t) = 1.0 + 6.0*lambda;
    A(t,t+1) = -4.0*lambda;
    A(t,t+2) = lambda;
end

%%%% Solve for Row N-1 %%%%
A(N-1,N-3) = lambda;
A(N-1,N-2) = -4.0*lambda;
A(N-1,N-1) = 1.0 + 5.0*lambda;
A(N-1,N) = -2.0*lambda;

%%%% Solve for Row T %%%%
A(N,N-2) = lambda;
A(N,N-1) = -2.0*lambda;
A(N,N) = 1.0 + lambda;

%%%% Create HP Trend %%%%
X_hat = inv(A)*X;

%%%% Detrend the Data %%%%
X_tilde = X - X_hat;